#include <sys/epoll.h>
#include "log.hpp"
#include <cerrno>
#include <cstring>
#include <unistd.h>

class Epoller
{
public:
    static const int size = 128;

    Epoller()
    {
        _epfd = epoll_create(size);
        if (_epfd == -1)
            lg(Error, "epoll_create code:%d msg: %s", errno, strerror(errno));
        else
            lg(Info, "epoll_create success: %d", _epfd);
    }

    int EpollUpdate(int op, int fd, uint32_t events)
    {
        int n = 0;
        if(op == EPOLL_CTL_DEL)
        {
            //EPOLL_CTL_DEL 可以不传最后一个参数，当然也可以传
            n = epoll_ctl(_epfd, op, fd, nullptr);
            if (n != 0)
            { 
                lg(Error, "epoll_ctl delete error!");
            }
        }
        else
        {
            struct epoll_event* Event = new struct epoll_event;
            Event->data.fd = fd;
            Event->events = events;
            n = epoll_ctl(_epfd, op, fd, Event);
            if (n != 0)
            {
                lg(Error, "epoll_ctl error!");
            }
        }
        return n;
    }

    int EpollWait(struct epoll_event* events, int maxevents)
    {
        int n = epoll_wait(_epfd, events, maxevents, -1);
        if(n < 0)
        {
            lg(Error, "epoll_wait error!");
        }
        return n;
    }

    ~Epoller()
    {
        //它也是个文件描述符，记得关
        if(_epfd >= 0)
            close(_epfd);
    }

private:
    int _epfd;
};